import { axios } from "../../utils/request"

// pages/dinner/dinner.ts
Page({
  /**
   * 页面的初始数据
   */
  data: {
    initData: [] as any[],
    array: [] as any[],
    show: false,
    price: 0,
  },
  //添加餐品到购物车
  addDinner(e: any) {
    let index = e.currentTarget.dataset.index
    let currentData = this.data.initData[index]
    currentData.index = index
    let array = this.data.array
    let price = 0
    if (array.length > 0) {
      let flag = array.some((item) => {
        //添加之前判断是否有重复
        return item.id == currentData.id
      })
      if (flag) {
        array.forEach((item, index) => {
          if (item.id == currentData.id) {
            array[index].count = item.count + 1
          }
        })
      } else {
        currentData.count = 1
        array.push(currentData)
      }
    } else {
      currentData.count = 1
      array.push(currentData)
    }
    array.forEach((item) => {
      price += item.count * item.price
    })
    this.setData({
      array,
      price,
    })
  },
  //减少餐品
  async decDinner(e: any) {
    let index = e.currentTarget.dataset.index
    let currentData = this.data.initData[index]
    let array = this.data.array
    let price = 0
    array.forEach((item, index) => {
      if (currentData.id == item.id) {
        if (item.count == 1) {
          array.splice(index, 1)
        } else {
          array[index].count = item.count - 1
        }
      }
    })
    array.forEach((item) => {
      price += item.count * item.price
    })
    this.setData({
      array,
      price,
    })
  },
  async onChange(e: any) {
    wx.showLoading({ title: "加载中", mask: true })
    let id = e.detail
    let result = (await axios(`/dinner/${id}`)) as Response
    this.setData({
      initData: result.data,
    })
    setTimeout(function () {
      wx.hideLoading()
    }, 200)
  },
  //确认支付
  onSubmit() {
    const isLogin = wx.getStorageSync("isLogin")
    if (isLogin) {
      wx.navigateTo({
        url: "/pages/dinnerConfirm/dinnerConfirm",
        success: (res) => {
          // 通过 eventChannel 向被打开页面传送数据
          let price = this.data.price
          let data = this.data.array
          res.eventChannel.emit("context", { price, data })
        },
      })
    } else {
      wx.navigateTo({ url: "/pages/login/login" })
    }
  },
  showPop() {
    this.setData({
      show: true,
    })
  },
  closePop() {
    this.setData({
      show: false,
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    wx.showLoading({
      title: "加载中",
      mask: true,
    })
    this.getTabBar().setData({
      active: 2,
    })
    let result = (await axios(`/dinner/0`)) as Response
    this.setData({
      initData: result.data,
    })
    setTimeout(function () {
      wx.hideLoading()
    }, 200)
  },
})
